package com.haifeng.sbtx.auth.exception;

import com.alibaba.fastjson.JSONObject;
import com.haifeng.sbtx.common.base.JsonSerializer;
import com.haifeng.sbtx.common.base.Rest;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>
 *  授权失败处理器
 * </p>
 *
 * @author: Haifeng
 * @date: 2019-12-15
 */
@Component("customAccessDeniedHandler")
public class CustomAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException)
            throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        Rest error = Rest.error(HttpStatus.UNAUTHORIZED.value(), accessDeniedException.getMessage());
        response.getWriter().write(JSONObject.toJSONString(error, JsonSerializer.serializerFeatures));
    }
}
